#!/bin/sh
#
# argtest -- test lsof arguments for stack overflows
#
# usage: argtest [path_to_lsof]
#
#   where:
#	    path_to_lsof	optional *absolute* path to lsof (default
#				${HOME}/src/lsof4/lsof)

ARG_A=`pwd`/argtest_a.$$
ARG_N=`pwd`/argtest_n.$$
ERR=0
SH=`pwd`/lsoftest.$$
SH1=`pwd`/lsoftestc.$$
T=`pwd`/argtest_tmp.$$
T1=`pwd`/argtest_tmp1.$$
trap 'rm -f $ARG_A $ARG_N $SH $SH1 $T $T1; exit 1' 1 2 3 15

# Decide how to use echo.

ECHO=`echo -n ""`
if test "X$ECHO" = "X-n "
then
  EC="\c"
  EO=""
else
  EC=""
  EO="-n"
fi

# Establish the lsof path.

if test $# -gt 0
then
  LSOF=$1
else
  LSOF=${HOME}/src/lsof4/lsof
fi

# Create temporary files that can be used as very large alphabetic
# and numeric arguments.

rm -f $ARG_A $T $T1
echo $EO "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ012345678901$EC" > $T
cp $T $T1
for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
do
  cat $T >> $T1
done
cp $T1 $ARG_A
for i in 1 2 3 4 5 6 7
do
  cat $T1 >> $ARG_A
done
rm -f $T $T1
ls -l $ARG_A
rm -f $ARG_N $T $T1
echo $EO "0123456789012345678901234567890123456789012345678901234567890123$EC" > $T
cp $T $T1
for i in 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
do
  cat $T >> $T1
done
cp $T1 $ARG_N
for i in 1 2 3 4 5 6 7
do
  cat $T1 >> $ARG_N
done
rm -f $T $T1
ls -l $ARG_N

# Create a temporary shell script to execute lsof with options that require
# arguments, and use the contents of $ARG_A and $ARG_N as the arguments.

rm -f $SH $SH1
echo "#!/bin/sh" > $SH
echo "#!/bin/sh" > $SH1
echo "$LSOF \$1 \`cat $ARG_A\`" >> $SH
echo "$LSOF -c/\`cat $ARG_A\`/" >> $SH1
echo "$LSOF \$1 \`cat $ARG_N\`" >> $SH
echo "$LSOF -c/\`cat $ARG_N\`/" >> $SH1
chmod +x $SH $SH1
ls -l $SH $SH1

for a in -A -c -c/ +c +d +D -e +e -f +f -F -g -i -i4 -i6 -i@ -i: -k +L -m +m -p -s -stcp: -sudp: -T -u -x -z -Z
do
  echo $EO "Testing: $a ... $EC"
  if test "X$a" = "X-c/"
  then
    $SH1 2>&1 | egrep "Memory fault|Segmentation fault|Bus Error" > /dev/null 2>&1
  else
    $SH $a 2>&1 | egrep "Memory fault|Segmentation fault|Bus Error" > /dev/null 2>&1
  fi
  if test $? -eq 0
  then
    echo "!!!!FAILED!!!!"
    ERR=1
  else
   echo "OK"
  fi
done
rm -f $ARG_A $ARG_N $SH $SH1 core
exit $ERR
